package service

import (
	"context"
	v1 "docker-api/api/v1"
	"docker-api/internal/model"
	"docker-api/internal/repository"
	"docker-api/pkg/cmd"
	"fmt"
)

type DockerImagesService interface {
	List(ctx context.Context) ([]v1.DockerImageResponse, error)
	Pull(ctx context.Context, imageName string) error
	Delete(ctx context.Context, imageId string) error
	Import(ctx context.Context, path string) error
	Tag(ctx context.Context, imageId string, newTag string, newName string) error
	Refresh(ctx context.Context) error
}

func NewDockerImagesService(
	service *Service,
	dockerImagesRepository repository.DockerImagesRepository,
) DockerImagesService {
	return &dockerImagesService{
		Service:                service,
		dockerImagesRepository: dockerImagesRepository,
	}
}

type dockerImagesService struct {
	*Service
	dockerImagesRepository repository.DockerImagesRepository
}

func (s *dockerImagesService) List(ctx context.Context) ([]v1.DockerImageResponse, error) {

	iamges, err := s.dockerImagesRepository.List(ctx)
	if err != nil {
		return nil, err
	}

	responses := make([]v1.DockerImageResponse, len(iamges))

	// 直接复制结构体字段，因为字段名称和类型完全匹配
	for i, iamge := range iamges {
		responses[i] = v1.DockerImageResponse{
			Id:           iamge.ID,
			Name:         iamge.Name,
			Tag:          iamge.Tag,
			Size:         iamge.Size,
			Created:      iamge.Created,
			Architecture: iamge.Architecture,
		}
	}
	return responses, nil
}

func (s *dockerImagesService) Pull(ctx context.Context, imageName string) error {
	return s.dockerImagesRepository.Pull(ctx, imageName)
}

func (s *dockerImagesService) Delete(ctx context.Context, imageId string) error {
	return s.dockerImagesRepository.Delete(ctx, imageId)
}

func (s *dockerImagesService) Import(ctx context.Context, path string) error {
	return s.dockerImagesRepository.Import(ctx, path)
}

func (s *dockerImagesService) Tag(ctx context.Context, imageId string, newTag string, newName string) error {
	return s.dockerImagesRepository.Tag(ctx, imageId, newTag, newName)
}

// Refresh 刷新镜像列表，清空现有数据并插入新数据
func (s *dockerImagesService) Refresh(ctx context.Context) error {
	// 1. 获取所有镜像ID
	imageIDs, err := cmd.GetAllImageIDs()
	if err != nil {
		return err
	}

	var images []model.DockerImage
	// 2. 遍历每个镜像ID，获取详细信息
	for _, id := range imageIDs {
		imageDetails, err := cmd.GetImageDetail(id)
		if err != nil {
			continue
		}
		images = append(images, imageDetails...)
	}

	// 3. 更新数据库
	if err := s.dockerImagesRepository.RefreshImages(ctx, images); err != nil {
		return fmt.Errorf("更新镜像数据失败: %w", err)
	}

	return nil
}
